﻿  function ViewModel(parent, auth, username) {
      var self = this;

      self.parent = parent;
      // non knockout variables - those that are not changable
      self.auth = auth;
      self.username = username;
      // knockout variables
      self.profiles = ko.observableArray([]);
      self.myProfiles = ko.observableArray([]);
      self.workingProfile = ko.observable(null);
      self.workingProfileBuffer = ko.observable(new Profile({ }));
      self.workingProfileId = ko.observable(null);
      self.flagId = ko.observable(null);
      self.profileViewMode = ko.observable("list");
      self.flagMode = ko.observable("list");
      self.listProfileViewMode = ko.observable(true);
      self.myListProfileViewMode = ko.observable(false);
      self.detailsProfileViewMode = ko.observable(false);
      self.editProfileViewMode = ko.observable(false);
      self.advancedSearchProfileViewMode = ko.observable(false);
      self.profileAdvancedSearch = ko.observable(new ExpertProfileAdvancedSearch({ }));
      self.selectedIndustryId = ko.observable(-1);
      self.selectedCountryId = ko.observable(-1);
      self.selectedCategoryId = ko.observable(-1);
      self.selectedSubcategoryId = ko.observable(-1);
      self.selectedJobType = ko.observable(-1);
      self.availableJobTypes = ko.observableArray([]);
      self.availabilityStatuses = ko.observableArray([]);
      self.levels = ko.observableArray([]);
      self.experiences = ko.observableArray([]);
      self.workingLanguageSkill = ko.observable(new LanguageSkill({ }));
      self.workingTechnologySkill = ko.observable(new TechnologySkill({ }));
      self.industryTags = ko.observableArray([]);
      self.categoryTags = ko.observableArray([]);
      self.technologyTags = ko.observableArray([]);
      self.educationTags = ko.observableArray([]);
      self.languageTags = ko.observableArray([]);
      self.countryTags = ko.observableArray([]);
      self.keywordTags = ko.observableArray([]);
      self.preKeywordTags = ko.observableArray([]);
      self.employmentTypeTags = ko.observableArray([]);
      self.availabilityStatusTag = ko.observable();
      self.excludedJobTypes = ko.observableArray([]);
      self.keyword = ko.observable("");
      self.enterKeyPressed = false;
      self.falseVar = ko.observable(false);
      self.lastIndustryTagId = ko.computed(function() {
          return self.industryTags().length != 0 ? self.industryTags()[self.industryTags().length - 1].Id : 0;
      });

      //RESET TAGS LISTS
      self.resetTagsLists = function() {
          self.countryTags([]);
          self.industryTags([]);
          self.categoryTags([]);
          self.technologyTags([]);
          self.educationTags([]);
          self.languageTags([]);
          self.keywordTags([]);
      };

      //JOB TYPES
      self.jobTypes = ko.observableArray([]);
      self.jobTypesDecode = ko.computed(function() {
          var list = new Array();
          if (self.workingProfile()) {
              for (var i = 0; i < self.availableJobTypes().length; i++) {
                  if ((self.availableJobTypes()[i].Value & self.workingProfile().JobType()) > 0) {
                      list.push(self.availableJobTypes()[i]);
                  }
              }
          }
          self.jobTypes(list);
      });

      self.excludeJobTypes = ko.computed(function() {
          // if workingProfilie changes and it is not null
          if (self.workingProfile()) {
              var newArray = new Array();
              // go through all available educations and select those that aren't inlcuded
              for (i in self.availableJobTypes()) {
                  var found = false;
                  var availableJobType = self.availableJobTypes()[i];
                  for (j in self.jobTypes()) {
                      var selectedJobType = self.jobTypes()[j];
                      if (availableJobType.Value == selectedJobType.Value) {
                          found = true;
                          break;
                      }
                  }
                  if (!found) {
                      newArray.push(availableJobType);
                  }
              }
              self.excludedJobTypes(newArray);
          }

      });
      self.addJobType = function(employment) {
          var array = [];
          if (employment.Value == 0) {
              for (var i = 0; i < self.availableJobTypes().length; i++) {
                  if (self.availableJobTypes()[i].Value != 0) {
                      array.push(self.availableJobTypes()[i]);
                  }
              }
              self.jobTypes(array);
          } else {
              self.jobTypes.push(employment);
          }
      };
      self.removeJobType = function(employment) {
          self.jobTypes.remove(employment);
      };

      self.allJobTypesBtnVisible = ko.computed(function() {
          if (self.workingProfile()) {
              if (self.excludedJobTypes().length > 1) {
                  return true;
              }
              return false;
          }
          return false;
      });

      self.loadEmploymentTypes = function() {
          $.getJSON("/ExpertProfile/GetJobTypes", function(jobTypes) {
              self.availableJobTypes(jobTypes);
          });
      };
      self.loadAvailabilityStatuses = function() {
          $.getJSON("/ExpertProfile/GetAvailabilityStatus", function(availabilityStatus) {
              self.availabilityStatuses(availabilityStatus);
          });
      };
      self.loadLevels = function() {
          $.getJSON("/ExpertProfile/GetLevels", function(levels) {
              self.levels(levels);
          });
      };
      self.loadExperiences = function() {
          $.getJSON("/ExpertProfile/GetExperiences", function(experiences) {
              self.experiences(experiences);
          });
      };

      self.availableIndustriesProfiles = ko.observableArray([]);
      self.countryNew = ko.observable(false);
      self.countryUpdate = ko.observable(false);


      self.inspectCountry = ko.computed(function() {
          if (self.workingProfile()) {
              if (self.workingProfile().Id() == 0) {
                  self.countryNew(true);
                  self.countryUpdate(false);
              } else {
                  self.countryNew(false);
                  self.countryUpdate(true);
              }
          }
      });

      self.inspectViewMode = ko.computed(function() {
          var mode = self.profileViewMode();
          if (mode == "list") {
              self.listProfileViewMode(true);
              self.detailsProfileViewMode(false);
              self.editProfileViewMode(false);
              self.advancedSearchProfileViewMode(false);
          } else if (mode == "myList") {
              self.listProfileViewMode(true);
              self.detailsProfileViewMode(false);
              self.editProfileViewMode(false);
              self.advancedSearchProfileViewMode(false);
          } else if (mode == "details") {
              self.listProfileViewMode(false);
              self.detailsProfileViewMode(true);
              self.editProfileViewMode(false);
              self.advancedSearchProfileViewMode(false);
          } else if (mode == "edit") {
              self.listProfileViewMode(false);
              self.detailsProfileViewMode(false);
              self.editProfileViewMode(true);
              self.advancedSearchProfileViewMode(false);
          } else if (mode == "advancedSearch") {
              self.listProfileViewMode(false);
              self.detailsProfileViewMode(false);
              self.editProfileViewMode(false);
              self.advancedSearchProfileViewMode(true);
          }
      });
      //SELECT PROFILE
      self.select = function(profile) {
          self.selectProfile(profile);
      };
      self.selectProfile = function(profile) {
          self.workingProfile(profile);
      };
      self.deselectProfile = function() {
          self.workingProfile(null);
      };
      self.selectNew = function() {
          var newProfile = new Profile({ });
          self.myProfiles.push(newProfile);
          self.selectProfile(newProfile);
          $.when(loadGoogleMaps(3, null, null))
              .then(function() {
                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                      var loc = self.workingProfile() ? self.workingProfile().Location() ? self.workingProfile().Location() + ", " + self.workingProfile().Country().Description() : "" : "";
                      $("#locationProfileEditMode").gmap3({
                              action: 'getAddress',
                              address: loc,
                              callback: function(results) {
                                  if (!results) return;
                                  $("#locationProfileEditMode").gmap3(
                                      { action: 'clear', name: 'marker' },
                                      { action: 'addMarker', latLng: results[0].geometry.location },
                                      { action: 'setCenter', args: [results[0].geometry.location] }
                            );
                              }
                          });
                  });
              });
          self.workingProfileId(self.workingProfile().Id());
          self.profileViewMode("edit");
          self.generateRoute();
      };
      self.selectEdit = function(profile) {
          self.select(profile);
          $.when(loadGoogleMaps(3, null, null))
              .then(function() {
                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                      var loc = self.workingProfile() ? self.workingProfile().Location() ? self.workingProfile().Location() + ", " + self.workingProfile().Country().Description : "" : "";
                      $("#locationProfileEditMode").gmap3({
                              action: 'getAddress',
                              address: loc,
                              callback: function(results) {
                                  if (!results) return;
                                  $("#locationProfileEditMode").gmap3(
                                      { action: 'clear', name: 'marker' },
                                      { action: 'addMarker', latLng: results[0].geometry.location },
                                      { action: 'setCenter', args: [results[0].geometry.location] }
                            );
                              }
                          });
                  });
              });
          self.workingProfileId(self.workingProfile().Id());
          self.profileViewMode("edit");
          self.generateRoute();
      };

      self.selectDetails = function(profile) {
          self.selectProfile(profile);
          $.when(loadGoogleMaps(3, null, null))
              .then(function() {
                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                      var loc = self.workingProfile() ? self.workingProfile().Location() ? self.workingProfile().Location() : "" : "";
                      $("#locationProfileViewMode").gmap3({
                              action: 'getAddress',
                              address: loc,
                              callback: function(results) {
                                  if (!results) return;
                                  $("#locationProfileViewMode").gmap3(
                                      { action: 'clear', name: 'marker' },
                                      { action: 'addMarker', latLng: results[0].geometry.location },
                                      { action: 'setCenter', args: [results[0].geometry.location] }
                                    );
                              }
                          });
                  });
              });
          self.workingProfileId(self.workingProfile().Id());
          self.profileViewMode("details");
          self.generateRoute();
      };
      self.selectMyDetails = function(profile) {
          self.selectProfile(profile);
          self.workingProfileId(self.workingProfile().Id());
          self.profileViewMode("myDetails");
          self.flagId(self.workingProfile().Id());
          self.flagMode("myDetails");
          // location.hash = "#/Experts/MyList/ProfileViewMode/";
      };

      self.selectAdvancedSearch = function() {
          self.initAdvancedSearchProfileModal();
      };
      //SIMPLE SEARCH
      self.simpleSearch = function() {
          self.profileAdvancedSearch().CountryIds([]);
          self.profileAdvancedSearch().CountryIds().push(self.selectedCountryId());
          self.profileAdvancedSearch().IndustryIds([]);
          self.profileAdvancedSearch().IndustryIds().push(self.selectedIndustryId());
          self.generateRoute();
      };
      //TOOLTIP
      self.categoryTooltip = ko.observable();
      self.showTooltip = function(category) {
          self.categoryTooltip(category.Description);
          $('.tableProfilesCategory').tooltip({
                  title: "Show all experts in category " + self.categoryTooltip(),
                  delay: { show: 500, hide: 100 }
              });
          $('.tableProfilesCategory').tooltip('show');
      };
      self.hideTooltip = function() {
          $('.tableProfilesCategory').tooltip('hide');
      };

      //RATES
      self.hourlyDailyRatesVisible = ko.observable(false);
      self.annualRatesVisible = ko.observable(false);
      self.checkRates = ko.computed(function() {
          if (self.workingProfile()) {
              if (self.jobTypes().length == 1) {
                  if (self.workingProfile().JobType() == 2) {
                      self.hourlyDailyRatesVisible(true);
                      self.annualRatesVisible(false);
                  } else {
                      self.hourlyDailyRatesVisible(false);
                      self.annualRatesVisible(true);
                  }
              } else if (self.jobTypes().length > 1) {
                  if ((self.workingProfile().JobType() & 2) > 0) {
                      self.hourlyDailyRatesVisible(true);
                      self.annualRatesVisible(true);
                  } else {
                      self.hourlyDailyRatesVisible(false);
                      self.annualRatesVisible(true);
                  }
              }
          }
      });
      self.hourlyDailyRatesSearchVisible = ko.observable(false);
      self.monthlyAnnualRatesSearchVisible = ko.observable(false);
      self.ratesSearchVisible = ko.observable(false);
      self.checkRatesSearch = ko.computed(function() {
          if (self.profileAdvancedSearch()) {
              if (self.profileAdvancedSearch().JobTypes().length == 1) {
                  self.ratesSearchVisible(true);
                  if (self.profileAdvancedSearch().JobType() == 2) {
                      self.hourlyDailyRatesSearchVisible(true);
                      self.monthlyAnnualRatesSearchVisible(false);
                  } else {
                      self.hourlyDailyRatesSearchVisible(false);
                      self.monthlyAnnualRatesSearchVisible(true);
                  }
              } else if (self.profileAdvancedSearch().JobTypes().length > 1) {
                  self.ratesSearchVisible(true);
                  if ((self.profileAdvancedSearch().JobType() & 2) > 0) {
                      self.hourlyDailyRatesSearchVisible(true);
                      self.monthlyAnnualRatesSearchVisible(true);
                  } else {
                      self.hourlyDailyRatesSearchVisible(false);
                      self.monthlyAnnualRatesSearchVisible(true);
                  }
              } else {
                  self.ratesSearchVisible(false);
              }
          }
      });

      self.resetAdvancedSearch = function() {
          self.profileAdvancedSearch(new ExpertProfileAdvancedSearch({ }));
          self.keywordTags([]);
          self.countryTags([]);
          self.industryTags([]);
          self.categoryTags([]);
          self.technologyTags([]);
          self.educationTags([]);
          self.languageTags([]);
          self.employmentTypeTags([]);
          self.availabilityStatusTag(null);
      };


      // many to many for education
      self.availableEducations = ko.observableArray([]);
      self.excludedEducations = ko.observableArray([]);

      // many to many for category
      self.availableCategories = ko.observableArray([]);
      self.breadCrumbCategories = ko.observableArray([{ Id: -1, Description: "Start" }]);

      self.availableCountriesProfiles = ko.observableArray([]);

      //CONTACT
      self.email = ko.observable();
      self.subject = ko.observable();
      self.body = ko.observable();
      self.contactSuccessfullVisible = ko.observable(false);

      self.resetContact = function() {
          self.email("");
          self.subject("");
          self.body("");
          self.contactSuccessfullVisible(false);
      };

      self.contactFreelancer = function() {
          $.post("/ExpertProfile/ContactFreelancer", { id: self.workingProfile().UserId(), Email: self.email(), Subject: self.subject(), Body: self.body() }, function() {
              self.contactSuccessfullVisible(true);
              setTimeout(function() { $("#ContactFreelancer").modal("hide"); }, 2500);
          });
      };
      self.cancelContactFreelancer = function() {
          $("#ContactFreelancer").modal("hide");
          self.resetContact();
      };
      self.selectProfileAndReset = function(profile) {
          self.workingProfile(profile);
          self.resetContact();
          self.initContactProfileModal();
      };

      //EMPLOYMENT TYPE
      self.employmentCheck = ko.observable("");
      self.checkEmployment = function() {
          if (self.workingProfile().EmploymentType() == 0) {
              self.employmentCheck("Permanent");
          } else if (self.workingProfile().EmploymentType() == 1) {
              self.employmentCheck("Freelancer");
          }
      };

      //AVAILABILITY STATUS
      self.availabilityCheck = ko.observable("");
      self.checkAvailability = function() {
          if (self.workingProfile().AvailabilityStatus() == 0) {
              self.availabilityCheck("Available");
          } else if (self.workingProfile().AvailabilityStatus() == 1) {
              self.availabilityCheck("Not available");
          } else if (self.workingProfile().AvailabilityStatus() == 2) {
              self.availabilityCheck("Partly available");
          }
      };

      //EMPLOYMENT TYPE - workingProfile()
      self.employmentCheckWorkingProfile = ko.observable("");
      self.checkEmploymentWorkingProfile = function() {
          if (self.workingProfile().EmploymentType() == 0) {
              self.employmentCheckWorkingProfile("Permanent");
          } else if (self.workingProfile().EmploymentType() == 1) {
              self.employmentCheckWorkingProfile("Freelancer");
          }
      };

      //AVAILABILITY STATUS -workingProfile()
      self.availabilityCheckWorkingProfile = ko.observable("");
      self.checkAvailabilityWorkingProfile = function() {
          if (self.workingProfile().AvailabilityStatus() == 0) {
              self.availabilityCheckWorkingProfile("Available");
          } else if (self.workingProfile().AvailabilityStatus() == 1) {
              self.availabilityCheckWorkingProfile("Not available");
          } else if (self.workingProfile().AvailabilityStatus() == 2) {
              self.availabilityCheckWorkingProfile("Partly available");
          }
      };

      //CATEGORIES
      self.getChildCategories = function(category) {
          $.getJSON('/ExpertProfile/GetChildCategories', category, function(result) {
              self.availableCategories(result);
          });
      };
      self.resetCategories = function() {
          self.getChildCategories(null);
          self.breadCrumbCategories([{ Id: -1, Description: "Start" }]);
      };
      self.selectBreadCrumbCategory = function(category) {
          var index = 0;
          var count = self.breadCrumbCategories().length;

          // find the index of the selected bread crumb category
          for (; index < count; index++) {
              if (self.breadCrumbCategories()[index].Id == category.Id) {
                  break;
              }
          }
          var deleteCount = count - index - 1;
          //returns the selected category
          if (deleteCount > 0) {
              self.breadCrumbCategories.splice(index + 1, deleteCount);
          }
          self.getChildCategories(category);
      };
      self.selectCatVisible = ko.observable(true);
      self.selectCatNotVisible = ko.observable(false);
      self.addCategory = function(category) {
          if (category.IsLeaf) {
              self.workingCategorySkill().CategoryName(category.Description);
              self.workingCategorySkill().CategoryId(category.Id);
              self.selectCatVisible(false);
              self.selectCatNotVisible(true);
          } else {
              self.breadCrumbCategories.push(category);
              self.getChildCategories(category);
          }
      };
      //CATEGORY SKILLS
      self.workingCategorySkill = ko.observable(new CategorySkill({ }));
      self.addCategorySkill = function() {
          var level = $.Enumerable.From(self.levels()).SingleOrDefault(null, function(x) {
              return self.workingCategorySkill().Level() === x.Value;
          });
          var experience = $.Enumerable.From(self.experiences()).SingleOrDefault(null, function(x) {
              return self.workingCategorySkill().Experience() === x.Value;
          });
          self.workingCategorySkill().LevelText(level.Description);
          self.workingCategorySkill().ExperienceText(experience.Description);

          var foundCategorySkill = self.workingProfile().Id() != 0 ?
              ko.utils.arrayFirst(self.workingProfileBuffer().CategorySkills(), function(item) {
                  return item.CategoryName == self.workingCategorySkill().CategoryName();
              }) :
              ko.utils.arrayFirst(self.workingProfileBuffer().CategorySkills(), function(item) {
                  return item.CategoryName() == self.workingCategorySkill().CategoryName();
              });
          if (!foundCategorySkill || foundCategorySkill == null) {
              self.workingProfileBuffer().CategorySkills.push(self.workingCategorySkill());
          }
      };
      self.removeCategorySkill = function(categorySkill) {
          self.workingProfileBuffer().CategorySkills.remove(categorySkill);
      };

      //LANGUAGE SKILLS
      self.selectedLanguage = ko.observable(null);
      self.newLanguageSkills = ko.observableArray([]);
      self.addLanguageSkill = function() {
          var level = $.Enumerable.From(self.levels()).SingleOrDefault(null, function(x) {
              return self.workingLanguageSkill().Level() === x.Value;
          });
          var newlanguageSkill = ko.observable(new LanguageSkill({
                  LanguageName: self.selectedLanguage().Description,
                  LanguageId: self.selectedLanguage().Id,
                  Level: self.workingLanguageSkill().Level(),
                  LevelText: level ? level.Description : ""
              }));

          var foundLanguageSkill = self.workingProfile().Id() != 0 ?
              ko.utils.arrayFirst(self.workingProfileBuffer().LanguageSkills(), function(item) {
                  return item.LanguageName == newlanguageSkill().LanguageName();
              }) :
              ko.utils.arrayFirst(self.workingProfileBuffer().LanguageSkills(), function(item) {
                  return item.LanguageName() == newlanguageSkill().LanguageName();
              });

          if (!foundLanguageSkill || foundLanguageSkill == null) {
              self.workingProfileBuffer().LanguageSkills.push(newlanguageSkill);
          }
      };
      self.removeLanguageSkill = function(languageSkill) {
          self.workingProfileBuffer().LanguageSkills.remove(function(item) { return item().LanguageName() == languageSkill.LanguageName(); });
      };

      //TECHNOLOGIES 
      self.availableTechnologies = ko.observableArray([]);
      self.loadTechnologies = function() {
          $.getJSON("/ExpertProfile/GetJsonTechnologies", function(allData) {
              self.availableTechnologies(allData);
          });
      };
      self.availableTechnologiesNames = ko.observableArray([]);
      self.loadTechnologiesNames = function() {
          $.getJSON("/ExpertProfile/GetJsonTechnologiesNames", function(allData) {
              self.availableTechnologiesNames(allData);
          });
      };
      self.technologyName = ko.observable("");
      self.createAndAddTechnology = function() {
          var newTech = $("#newTechProfile").val();
          self.technologyName(newTech);
          $.getJSON("/ExpertProfile/CreateTechnology", { technologyName: self.technologyName() }, function(technologyArray) {
              var mappedTechnologies = $.map(technologyArray, function(item) { return new Technology(item); });
              for (var i = 0; i < mappedTechnologies.length; i++) {
                  self.availableTechnologies().push(mappedTechnologies[i]);
              }
              $("#newTechProfile").val("");
          });
      };
      //TECHNOLOGY SKILLS
      self.selectedTechnology = ko.observable();
      self.addTechnologySkill = function() {
          var level = $.Enumerable.From(self.levels()).SingleOrDefault(null, function(x) {
              return self.workingTechnologySkill().Level() === x.Value;
          });
          var experience = $.Enumerable.From(self.experiences()).SingleOrDefault(null, function(x) {
              return self.workingTechnologySkill().Experience() === x.Value;
          });
          self.workingTechnologySkill().LevelText(level.Description);
          self.workingTechnologySkill().ExperienceText(experience.Description);
          self.workingTechnologySkill().TechnologyName($("#tSkillProfileEditMode").val());

          var foundTechnologySkill = self.workingProfile().Id() != 0 ?
              ko.utils.arrayFirst(self.workingProfileBuffer().TechnologySkills(), function(item) {
                  return item.TechnologyName == self.workingTechnologySkill().TechnologyName();
              }) :
              ko.utils.arrayFirst(self.workingProfileBuffer().TechnologySkills(), function(item) {
                  return item.TechnologyName() == self.workingTechnologySkill().TechnologyName();
              });

          if (!foundTechnologySkill || foundTechnologySkill == null) {
              self.workingProfileBuffer().TechnologySkills.push(self.workingTechnologySkill());
          }
      };
      self.removeTechnologySkill = function(technologySkill) {
          self.workingProfileBuffer().TechnologySkills.remove(technologySkill);
      };
      self.autocompleteTechnologiesEditMode = function() {
          $("#tSkillProfileEditMode").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Technology/GetTechnologiesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Name,
                                          value: item.Name
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

//                  var found = ko.utils.arrayFirst(self.technologyTags(), function (item) {
//                      return item.Description == description;
//                  });
//                  if (!found) {
//                      self.technologyTags.push({ Id: id, Description: description });
//                      self.PositionAdvancedSearch().TechnologyIds.push(id);
//                  }

//                  $("#tSkillProfileEditMode").val("");
//                  return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      //EDUCATION SKILLS
      self.workingEducationSkill = ko.observable(new EducationSkill({ }));
      self.educSkillPlusButtonVisible = ko.observable(true);
      self.educSkillOkButtonVisible = ko.observable(false);
      self.educSkillAlertVisible = ko.observable(false);
      self.workingESkillVisible = ko.observable(true);
      self.workingESkillNotVisible = ko.observable(false);
      self.addEducationSkill = function() {
          if (self.workingEducationSkill().errors().length == 0) {
              var eSkill = new EducationSkill({
                      Program: self.workingEducationSkill().Program(),
                      University: self.workingEducationSkill().University(),
                      StartYear: self.workingEducationSkill().StartYear(),
                      EndYear: self.workingEducationSkill().EndYear(),
                      EducationId: self.workingEducationSkill().EducationId(),
                      EducationName: $('#eSkillProfile option:selected').text()
                  });
              self.workingProfileBuffer().EducationSkills.push(eSkill);
              self.workingEducationSkill(new EducationSkill({ }));
              self.educSkillAlertVisible(false);
          } else {
              self.educSkillAlertVisible(true);
          }
          self.workingESkillVisible(false);
          self.workingESkillNotVisible(true);
      };
      self.editEducationSkill = function(educationSkill) {
          self.workingEducationSkill(educationSkill);
          self.educSkillPlusButtonVisible(false);
          self.educSkillOkButtonVisible(true);
          self.workingESkillVisible(true);
          self.workingESkillNotVisible(false);
      };
      self.okEducationSkill = function() {
          if (self.workingEducationSkill().errors().length == 0) {
              self.workingEducationSkill(new EducationSkill({ }));
              self.educSkillPlusButtonVisible(true);
              self.educSkillOkButtonVisible(false);
              self.educSkillAlertVisible(false);
          } else {
              self.educSkillAlertVisible(true);
          }
          self.workingESkillVisible(false);
          self.workingESkillNotVisible(true);
      };
      self.removeEducationSkill = function(educationSkill) {
          self.workingProfileBuffer().EducationSkills.remove(educationSkill);
      };

      //PAGING
      self.pagesCount = ko.observable(1);
      self.count = ko.observable(0);
      self.lastPage = function() {
          self.profileAdvancedSearch().PageIndex(self.pagesCount() - 1);
          self.generateRoute();
      };
      self.firstPage = function() {
          self.profileAdvancedSearch().PageIndex(0);
          self.generateRoute();
      };
      self.nextPage = function() {
          if (self.profileAdvancedSearch().PageIndex() < self.pagesCount() - 1) {
              self.profileAdvancedSearch().PageIndex(self.profileAdvancedSearch().PageIndex() + 1);
          }
          self.generateRoute();
      };
      self.previousPage = function() {
          if (self.profileAdvancedSearch().PageIndex() > 0) {
              self.profileAdvancedSearch().PageIndex(self.profileAdvancedSearch().PageIndex()() - 1);
          }
          self.generateRoute();
      };
      self.pageNumber = function(number) {
          self.profileAdvancedSearch().PageIndex(number);
          self.generateRoute();
      };
      self.fromPageNumber = ko.observable();
      self.fromPageNumberFun = function() {
          self.fromPageNumber((self.profileAdvancedSearch().PageSize() * (self.profileAdvancedSearch().PageIndex() + 1)) -
              (self.profileAdvancedSearch().PageSize() - 1));
      };
      self.toPageNumber = ko.observable();
      self.toPageNumberFun = function() {
          self.toPageNumber(self.profileAdvancedSearch().PageSize() *
              (self.profileAdvancedSearch().PageIndex() + 1));
      };

      self.pageSize = ko.observable(3);
      self.pageSize.subscribe(function(newValue) {
          self.profileAdvancedSearch().PageSize(newValue);
          if (parent.route() == "experts") {

              self.generateRoute();
          }

      });


      //CENTER MODALS
      self.centerContactProfileModal = function() {
          $('#ContactFreelancer').on('shown', function() {
              var modal;
              modal = $(this);
              modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
              return this;
          });
      };
      self.centerEducationSkillsProfileModal = function() {
          $('#EducationProfileDialog').on('shown', function() {
              var modal;
              modal = $(this);
              modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
              return this;
          });
      };
      self.centerCategorySkillsProfileModal = function() {
          $('#CategoriesProfileDialog').on('shown', function() {
              var modal;
              modal = $(this);
              modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
              return this;
          });
      };
      self.centerLanguageSkillsProfileModal = function() {
          $('#LanguageSkillsProfileDialog').on('shown', function() {
              var modal;
              modal = $(this);
              modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
              return this;
          });
      };
      self.centerTechnologySkillsProfileModal = function() {
          $('#TechnologySkillsProfileDialog').on('shown', function() {
              var modal;
              modal = $(this);
              modal.css('margin-top', (modal.outerHeight() / 2) * -1).css('margin-left', (modal.outerWidth() / 2) * -1);
              return this;
          });
      };

      //EDIT MODE-EDIT PROFILE
      self.selectName = function() {
          self.workingProfileBuffer().Title(self.workingProfile().Title());

      };
      self.okName = function() {
          if (self.workingProfileBuffer().Title.isValid()) {
              self.workingProfile().Title(self.workingProfileBuffer().Title());
              $("#NameProfileDialog").modal("hide");
          }
      };
      self.cancelName = function() {
          $("#NameProfileDialog").modal("hide");
      };
      self.selectDescription = function() {
          self.workingProfileBuffer().Description(self.workingProfile().Description());
      };
      self.okDescription = function() {
          if (self.workingProfileBuffer().Description.isValid()) {
              self.workingProfile().Description(self.workingProfileBuffer().Description());
              $("#DescriptionProfileDialog").modal("hide");
          }
      };
      self.cancelDescription = function() {
          $("#DescriptionProfileDialog").modal("hide");
      };
      self.selectLocation = function() {
          $.when(loadGoogleMaps(3, null, null))
              .then(function() {
                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                      var loc = self.workingProfile() ? self.workingProfile().Location() ? self.workingProfile().Location() : "" : "";
                      $("#locationAutocompleteProfile").val(loc);
                      $("#locationProfile").gmap3({
                              action: 'getAddress',
                              address: loc,
                              callback: function(results) {
                                  if (!results) return;
                                  $("#locationProfile").gmap3(
                                      { action: 'clear', name: 'marker' },
                                      { action: 'addMarker', latLng: results[0].geometry.location },
                                      { action: 'setCenter', args: [results[0].geometry.location] },
                                      { action: 'clear', name: 'InfoWindow' },
                                      {
                                          action: 'addInfoWindow',
                                          address: loc,
                                          map: {
                                              center: true,
                                              zoom: 10
                                          },
                                          infowindow: {
                                              options: { content: loc }
                                          }
                                      }
                            );
                              }
                          });
                  });
              });
          self.gmapLocationAutocomplete();

      };
      self.okLocation = function() {
          var location = $("#locationAutocompleteProfile").val();
          self.workingProfile().Location(location);
          self.locationMapVisible(true);
          $("#LocationProfileDialog").modal("hide");
      };
      self.cancelLocation = function() {
          $("#LocationProfileDialog").modal("hide");
      };
      self.selectJobType = function() {
          self.workingProfileBuffer().JobType(self.workingProfile().JobType());
      };
      self.okJobType = function() {
          var result;
          if (self.jobTypes().length == 0) {
              result = 0;
          } else {
              result = self.jobTypes()[0].Value;
              for (var i = 1; i < self.jobTypes().length; i++) {
                  result = result | self.jobTypes()[i].Value;
              }
          }
          self.workingProfile().JobType(result);
          $("#JobTypeProfileDialog").modal("hide");
      };
      self.cancelJobType = function() {
          $("#JobTypeProfileDialog").modal("hide");
      };
      self.selectHourDayRates = function() {
          self.workingProfileBuffer().HourRate(self.workingProfile().HourRate());
          self.workingProfileBuffer().DailyRate(self.workingProfile().DailyRate());
      };
      self.okHourDayRates = function() {
          if (self.workingProfileBuffer().HourRate.isValid() && self.workingProfile().DailyRate.isValid()) {
              self.workingProfile().HourRate(self.workingProfileBuffer().HourRate());
              self.workingProfile().DailyRate(self.workingProfileBuffer().DailyRate());
              $("#HourDayRatesProfileDialog").modal("hide");
          }
      };
      self.cancelHourDayRates = function() {
          $("#HourDayRatesProfileDialog").modal("hide");
      };
      self.selectMonthlyAnnualRates = function() {
          self.workingProfileBuffer().AnnualRate(self.workingProfile().AnnualRate());
          self.workingProfileBuffer().MonthlyRate(self.workingProfile().MonthlyRate());
      };
      self.okMonthlyAnnualRates = function() {
          if (self.workingProfileBuffer().errors().length == 0) {
              self.workingProfile().AnnualRate(self.workingProfileBuffer().AnnualRate());
              self.workingProfile().MonthlyRate(self.workingProfileBuffer().MonthlyRate());
              $("#AnnualRatesProfileDialog").modal("hide");
          }
      };
      self.cancelMonthlyAnnualRates = function() {
          $("#AnnualRatesProfileDialog").modal("hide");
      };
      self.selectCommentRates = function() {
          self.workingProfileBuffer().CommentRate(self.workingProfile().CommentRate());
      };
      self.okCommentRates = function() {
          if (self.workingProfileBuffer().CommentRate.isValid()) {
              self.workingProfile().CommentRate(self.workingProfileBuffer().CommentRate());
              $("#CommentRatesProfileDialog").modal("hide");
          }
      };
      self.cancelCommentRates = function() {
          $("#CommentRatesProfileDialog").modal("hide");
      };
      self.selectWebsite = function() {
          self.workingProfileBuffer().Website(self.workingProfile().Website());
      };
      self.okWebsite = function() {
          if (self.workingProfileBuffer().Website.isValid()) {
              self.workingProfile().Website(self.workingProfileBuffer().Website());
              $("#WebsiteProfileDialog").modal("hide");
          }
      };
      self.cancelWebsite = function() {
          $("#WebsiteProfileDialog").modal("hide");
      };
      self.selectSkype = function() {
          self.workingProfileBuffer().Skype(self.workingProfile().Skype());
      };
      self.okSkype = function() {
          if (self.workingProfileBuffer().Skype.isValid()) {
              self.workingProfile().Skype(self.workingProfileBuffer().Skype());
              $("#SkypeProfileDialog").modal("hide");
          }
      };
      self.cancelSkype = function() {
          $("#SkypeProfileDialog").modal("hide");
      };
      self.selectFacebook = function() {
          self.workingProfileBuffer().Facebook(self.workingProfile().Facebook());
      };
      self.okFacebook = function() {
          if (self.workingProfileBuffer().Facebook.isValid()) {
              self.workingProfile().Facebook(self.workingProfileBuffer().Facebook());
              $("#FacebookProfileDialog").modal("hide");
          }
      };
      self.cancelFacebook = function() {
          $("#FacebookProfileDialog").modal("hide");
      };
      self.selectTwitter = function() {
          self.workingProfileBuffer().Twitter(self.workingProfile().Twitter());
      };
      self.okTwitter = function() {
          if (self.workingProfileBuffer().Twitter.isValid()) {
              self.workingProfile().Twitter(self.workingProfileBuffer().Twitter());
              $("#TwitterProfileDialog").modal("hide");
          }
      };
      self.cancelTwitter = function() {
          $("#TwitterProfileDialog").modal("hide");
      };
      self.selectLinkedin = function() {
          self.workingProfileBuffer().Linkedin(self.workingProfile().Linkedin());
      };
      self.okLinkedin = function() {
          if (self.workingProfileBuffer().Linkedin.isValid()) {
              self.workingProfile().Linkedin(self.workingProfileBuffer().Linkedin());
              $("#LinkedinProfileDialog").modal("hide");
          }
      };
      self.cancelLinkedin = function() {
          $("#LinkedinProfileDialog").modal("hide");
      };
      self.selectEducation = function() {
          self.loadEducations();
          self.workingProfileBuffer().EducationSkills(self.workingProfile().EducationSkills());
      };
      self.okEducation = function() {
          self.workingProfile().EducationSkills(self.workingProfileBuffer().EducationSkills());
          $("#EducationProfileDialog").modal("hide");
      };
      self.cancelEducation = function() {
          $("#EducationProfileDialog").modal("hide");
      };
      self.selectCategories = function() {
          self.selectCatVisible(true);
          self.selectCatNotVisible(false);
          self.getChildCategories();
          self.workingProfileBuffer().CategorySkills(self.workingProfile().CategorySkills());
      };
      self.okCategories = function() {
          self.resetCategories();
          self.workingProfile().CategorySkills(self.workingProfileBuffer().CategorySkills());
          $("#CategoriesProfileDialog").modal("hide");
      };
      self.cancelCategories = function() {
          self.resetCategories();
          $("#CategoriesProfileDialog").modal("hide");
      };
      self.selectLanguageSkills = function() {
          self.loadLanguages();
          self.workingProfileBuffer().LanguageSkills(self.workingProfile().LanguageSkills());
      };
      self.okLanguageSkills = function() {
          self.workingProfile().LanguageSkills(self.workingProfileBuffer().LanguageSkills());
          $("#LanguageSkillsProfileDialog").modal("hide");
      };
      self.cancelLanguageSkills = function() {
          $("#LanguageSkillsProfileDialog").modal("hide");
      };
      self.selectTechnologySkills = function() {
          self.loadTechnologies();
          self.loadTechnologiesNames();
          self.workingProfileBuffer().TechnologySkills(self.workingProfile().TechnologySkills());
      };
      self.okTechnologySkills = function() {
          self.workingProfile().TechnologySkills(self.workingProfileBuffer().TechnologySkills());
          $("#TechnologySkillsProfileDialog").modal("hide");
      };
      self.cancelTechnologySkills = function() {
          $("#TechnologySkillsProfileDialog").modal("hide");
      };
      self.selectExperience = function() {
          self.workingProfileBuffer().Experience(self.workingProfile().Experience());
      };
      self.okExperience = function() {
          if (self.workingProfileBuffer().Experience.isValid()) {
              self.workingProfile().Experience(self.workingProfileBuffer().Experience());
              $("#ExperienceProfileDialog").modal("hide");
          }
      };
      self.cancelExperience = function() {
          $("#ExperienceProfileDialog").modal("hide");
      };
      self.selectReferences = function() {
          self.workingProfileBuffer().References(self.workingProfile().References());
      };
      self.okReferences = function() {
          if (self.workingProfileBuffer().References.isValid()) {
              self.workingProfile().References(self.workingProfileBuffer().References());
              $("#ReferencesProfileDialog").modal("hide");
          }
      };
      self.cancelReferences = function() {
          $("#ReferencesProfileDialog").modal("hide");
      };
      self.selectAvailability = function() {
          self.workingProfileBuffer().Availability(self.workingProfile().Availability());
      };
      self.okAvailability = function() {
          if (self.workingProfileBuffer().Availability.isValid()) {
              self.workingProfile().Availability(self.workingProfileBuffer().Availability());
              $("#AvailabilityProfileDialog").modal("hide");
          }
      };
      self.cancelAvailability = function() {
          $("#AvailabilityProfileDialog").modal("hide");
      };
      self.selectOther = function() {
          self.workingProfileBuffer().Other(self.workingProfile().Other());
      };
      self.okOther = function() {
          if (self.workingProfileBuffer().Other.isValid()) {
              self.workingProfile().Other(self.workingProfileBuffer().Other());
              $("#OtherProfileDialog").modal("hide");
          }
      };
      self.cancelOther = function() {
          $("#OtherProfileDialog").modal("hide");
      };
      self.selectEmail = function() {
          self.workingProfileBuffer().Email(self.workingProfile().Email());
      };
      self.okEmail = function() {
          if (self.workingProfileBuffer().Email.isValid()) {
              self.workingProfile().Email(self.workingProfileBuffer().Email());
              $("#EmailProfileDialog").modal("hide");
          }
      };
      self.cancelEmail = function() {
          $("#EmailProfileDialog").modal("hide");
      };
      self.selectPhoneNumber = function() {
          self.workingProfileBuffer().PhoneNumber(self.workingProfile().PhoneNumber());
      };
      self.okPhoneNumber = function() {
          if (self.workingProfileBuffer().PhoneNumber.isValid()) {
              self.workingProfile().PhoneNumber(self.workingProfileBuffer().PhoneNumber());
              $("#PhoneNumberProfileDialog").modal("hide");
          }
      };
      self.cancelPhoneNumber = function() {
          $("#PhoneNumberProfileDialog").modal("hide");
      };
      self.selectCountry = function() {
          //for update mode
          if (self.workingProfile().Id() != 0) {
              var country = $.Enumerable.From(parent.availableCountriesWithoutAll()).SingleOrDefault(null, function(x) {
                  return self.workingProfile().Country().Id === x.Id;
              });
              if (country != null) {
                  self.workingProfileBuffer().Country(country);
              }
              $("#CountryUpdateProfileDialog").modal("show");
          }
              //for create new mode
          else {
              $("#CountryProfileDialog").modal("show");
          }
      };
      self.okCountry = function() {
          if (self.workingProfileBuffer().Country.isValid()) {
              self.workingProfile().Country(self.workingProfileBuffer().Country());
              if (self.workingProfile().Id() == 0) {
                  $("#CountryProfileDialog").modal("hide");
              } else {
                  $("#CountryUpdateProfileDialog").modal("hide");
              }
          }
      };
      self.cancelCountry = function() {
          if (self.workingProfile().Id() == 0) {
              $("#CountryProfileDialog").modal("hide");
          } else {
              $("#CountryUpdateProfileDialog").modal("hide");
          }
      };
      self.selectIndustry = function() {
          //update mode
          if (self.workingProfile().Id() != 0) {
              var industry = $.Enumerable.From(parent.availableIndustriesWithoutAll()).SingleOrDefault(null, function(x) {
                  return self.workingProfile().Industry().Id === x.Id;
              });
              if (industry != null) {
                  self.workingProfileBuffer().Industry(industry);
              }
              $("#IndustryUpdateProfileDialog").modal("show");
          }
              //create new mode
          else {
              $("#IndustryProfileDialog").modal("show");
          }
      };
      self.okIndustry = function() {
          if (self.workingProfileBuffer().Industry.isValid()) {
              self.workingProfile().Industry(self.workingProfileBuffer().Industry());
              if (self.workingProfile().Id() == 0) {
                  $("#IndustryProfileDialog").modal("hide");
              } else {
                  $("#IndustryUpdateProfileDialog").modal("hide");
              }
          }
      };
      self.cancelIndustry = function() {
          if (self.workingProfile().Id() == 0) {
              $("#IndustryProfileDialog").modal("hide");
          } else {
              $("#IndustryUpdateProfileDialog").modal("hide");
          }
      };
      self.selectAvailabilityStatus = function() {
          self.workingProfileBuffer().AvailabilityStatus(self.workingProfile().AvailabilityStatus());
      };
      self.okAvailabilityStatus = function() {
          self.workingProfile().AvailabilityStatus(self.workingProfileBuffer().AvailabilityStatus());
          var availabilityStatus = $.Enumerable.From(self.availabilityStatuses()).SingleOrDefault(null, function(x) {
              return self.workingProfile().AvailabilityStatus() === x.Value;
          });
          if (availabilityStatus != null) {
              self.workingProfile().AvailabilityStatusText(availabilityStatus.Description);
          }
          $("#AvailabilityStatusProfileDialog").modal("hide");
      };
      self.cancelAvailabilityStatus = function() {
          $("#AvailabilityStatusProfileDialog").modal("hide");
      };
      self.okPhoto = function() {
          if (self.workingProfileBuffer().Photo.isValid()) {
              self.workingProfile().Photo(self.workingProfileBuffer().Photo());
              self.resetPhotoUpload();
              $("#ProfilePhotoProfileDialog").modal("hide");
          }
      };
      self.cancelPhoto = function() {
          self.resetPhotoUpload();
          $("#ProfilePhotoProfileDialog").modal("hide");
      };
      self.checkPhoto = ko.computed(function() {
          if (self.workingProfile()) {
              var photo = self.workingProfile().Photo();
              self.workingProfile().Photo150X150(photo.replace("/250X250_", "/150X150_"));
              self.workingProfile().Photo80X80(photo.replace("/250X250_", "/80X80_"));
          }
      });
      self.okCv = function() {
          if (self.workingProfileBuffer().Cv.isValid()) {
              self.workingProfile().Cv(self.workingProfileBuffer().Cv());
              self.resetCvUpload();
              $("#CvProfileDialog").modal("hide");
          }
      };
      self.cancelCv = function() {
          self.resetCvUpload();
          $("#CvProfileDialog").modal("hide");
      };
      //LOCATION VISIBILITY
      self.locationMapVisible = ko.observable(false);
      self.locationVisible = ko.observable(false);
      self.isLocationVisible = ko.computed(function() {
          if (self.workingProfile()) {
              if (self.workingProfile().Country() != null) {
                  self.locationVisible(true);
              }
          }
      });

      // CATEGORY/TECHNOLOGY SKILLS VISIBILITY
      self.catTechSkillsVisible = ko.observable(false);
      self.areCatTechskillsVisible = ko.computed(function() {
          if (self.workingProfile()) {
              if (self.workingProfile().Industry() != null) {
                  self.catTechSkillsVisible(true);
              }
          }
      });

      self.nameVisible = ko.observable(true);
      self.isNameVisible = ko.computed(function() {
          if (self.workingProfile() != null) {
              if (self.workingProfile().Title() != null && self.workingProfile().Title() != "") {
                  self.nameVisible(false);
              }
          }
      });
      self.descriptionVisible = ko.observable(true);
      self.isDescriptionVisible = ko.computed(function() {
          if (self.workingProfile() != null) {
              if (self.workingProfile().Description() != null && self.workingProfile().Description() != "") {
                  self.descriptionVisible(false);
              }
          }
      });
      self.alertVisible = ko.observable(false);
      self.tableOfProfilesVisible = ko.observable(false);
      self.youAreNotAllowedAlertVisible = ko.observable(false);
      self.SaveOrUpdate = function() {
          if (self.workingProfile().Id() == 0) {
              if (self.workingProfile().errors().length == 0) {
                  self.workingProfile().CountryId(self.workingProfile().Country().Id);
                  self.workingProfile().IndustryId(self.workingProfile().Industry().Id);
                  $.ajax({
                          url: "/ExpertProfile/Save",
                          type: 'post',
                          data: ko.toJSON(self.workingProfile()),
                          contentType: 'application/json',
                          success: function(id) {
                              self.workingProfile().Id(id);
                              self.selectDetails(self.workingProfile());
                          }
                      });
              } else {
                  self.alertVisible(true);
              }
          } else {
              if (self.workingProfile().errors().length == 0) {
                  self.workingProfile().CountryId(self.workingProfile().Country().Id);
                  self.workingProfile().IndustryId(self.workingProfile().Industry().Id);
                  $.ajax({
                          url: "/ExpertProfile/Update",
                          type: 'post',
                          data: ko.toJSON(self.workingProfile()),
                          contentType: 'application/json',
                          success: function(result) {
                              if (result != "ERROR") {
                                  self.selectDetails(self.workingProfile());
                              } else {
                                  self.tableOfProfilesVisible(false);
                                  self.youAreNotAllowedAlertVisible(true);
                              }
                          }
                      });
              } else {
                  self.alertVisible(true);
              }
          }
      };
      self.Delete = function() {
          $.ajax({
              url: "/api/ExpertProfile/DeleteExpertProfile",
              type: 'post',
              data: self.workingProfile().Id(),
              contentType: 'application/json',
              statusCode: {
                  200: function () {
                      self.profiles.remove(function (item) { return item.Id() == self.workingProfile().Id(); });
                      if (self.profileViewMode() == "details") {
                          self.profileViewMode("myList");
                      }
                      $('#DeleteDialog').modal('hide');
                  }
              }
          });
      };

      self.CancelDelete = function() {
          $('#DeleteDialog').modal('hide');
      };
      //SET COUNTRYID
      self.countryId = ko.observable(0);
      self.setCountryId = function (profile) {
          self.profileAdvancedSearch().CountryIds().push(profile.CountryId());
          self.selectedCountryId(profile.CountryId());
          self.generateRoute();
      };
      //SET INDUSTRYID
      self.industryId = ko.observable(0);
      self.setIndustryId = function(industry) {
          self.profileAdvancedSearch().IndustryIds().push(industry.Id);
          self.selectedIndustryId(industry.Id);
          self.generateRoute();
      };
      //SET CATEGORYID
      self.categoryId = ko.observable(0);
      self.setCategoryId = function(categorySkill) {
          self.profileAdvancedSearch().CategoryIds().push(categorySkill.CategoryId);
          //self.selectedCategoryId(categorySkill.CategoryId);
          self.selectedSubcategoryId(categorySkill.CategoryId);
          self.generateRoute();
      };
      //SET TECHNOLOGYID
      self.technologyId = ko.observable(0);
      self.setTechnologyId = function(technologySkill) {
          self.profileAdvancedSearch().TechnologyIds().push(technologySkill.TechnologyId);
          self.generateRoute();
      };

      self.resetIds = function() {
          self.industryId(0);
          self.categoryId(0);
          self.technologyId(0);
      };

      self.setListRoute = function() {
          self.resetSearchModel();
          self.profileAdvancedSearch().UserId(0);
          self.profileViewMode("list");
          self.generateRoute();
      };
      self.setMyListRoute = function () {
          self.resetSearchModel();
          self.profileAdvancedSearch().UserId(1);
          self.profileViewMode("myList");
          self.loadProfilesAdvancedSearchAll();
      };
      self.userSignedIn = ko.observable(false);
      self.signedIn = function() {
          $.ajax({
                  url: "/ExpertProfile/CheckSignedIn",
                  type: 'post',
                  data: { ExpertProfileId: self.workingProfile().Id() },
                  success: function(result) {
                      self.userSignedIn(result);
                  }
              });
      };
      self.editDeleteNewButton = ko.observable(false);
      self.messageButton = ko.observable(true);
      self.editDeleteNewButtonsVisible = ko.computed(function() {
          var mode = self.profileViewMode();
          //check if user is signed in
          if (mode == "details") {
              self.signedIn();
          }
          if (mode == "myList" || self.userSignedIn()) {
              self.editDeleteNewButton(true);
              self.messageButton(false);
          } else {
              self.editDeleteNewButton(false);
              self.messageButton(true);
          }
      });
      self.noResultsMessageVisible = ko.observable(false);
      self.loadProfilesAdvancedSearchAll = function() {
          if (self.profileViewMode() == "list" || self.profileViewMode() == "myList") {
              self.noResultsMessageVisible(false);
              $.ajax({
                      url: "/api/ExpertProfileApi/ListAdvancedSearchAll",
                      //url: "/ExpertProfile/ListAdvancedSearchAll",
                      type: 'POST',
                      dataType: 'json',
                      //crossDomain: true,
                      data: ko.toJSON(self.profileAdvancedSearch()),
                      contentType: "application/json",
                      success: function(allData) {
                          self.pagesCount(allData.PagesCount);
                          self.count(allData.Count);
                          var mappedProfiles = $.map(allData.Entities, function(item) { return new Profile(item); });
                          self.profiles(mappedProfiles);
                      }
                  });
              self.fromPageNumberFun();
              self.toPageNumberFun();
          }
      };

      self.showAllMyExperts = function() {
          self.profileAdvancedSearch().ShowAll(true);
          self.loadProfilesAdvancedSearchAll();
      };
      self.showLessMyExperts = function () {
          self.profileAdvancedSearch().ShowAll(false);
          self.loadProfilesAdvancedSearchAll();
      };
      
      //set profile as default
      self.setAsDefault = function (profile) {
          $.ajax({
              url: "/ExpertProfile/SetAsDefault",
              type: 'post',
              data: ko.toJSON(profile),
              contentType: 'application/json',
              success: function () {
                  self.setMyListRoute();
                  parent.company.setMyListRoute();
                  parent.position.setMyListRoute();
              }
          });
      };

      self.search = function() {
          self.noResultsMessageVisible(false);
          if (self.profileAdvancedSearch().CountryIds().length == 1) {
              self.selectedCountryId(self.profileAdvancedSearch().CountryIds()[0]);
          }
          if (self.profileAdvancedSearch().IndustryIds().length == 1) {
              self.selectedIndustryId(self.profileAdvancedSearch().IndustryIds()[0]);
          }
          if (self.profileAdvancedSearch().JobTypes().length == 1) {
              self.selectedJobType(self.profileAdvancedSearch().JobTypes()[0]);
          }
          $.ajax({
                  url: "/ExpertProfile/ListAdvancedSearchAll",
                  type: 'post',
                  data: ko.toJSON(self.profileAdvancedSearch()),
                  contentType: "application/json",
                  success: function(allData) {
                      self.pagesCount(allData.PagesCount);
                      self.count(allData.Count);
                      var mappedProfiles = $.map(allData.Entities, function(item) { return new Profile(item); });
                      self.profiles(mappedProfiles);
                      if (self.profiles().length == 0) {
                          self.profileViewMode("list");
                          self.tableOfProfilesVisible(false);
                          self.noResultsMessageVisible(true);
                      } else {
                          self.tableOfProfilesVisible(true);
                          self.noResultsMessageVisible(false);
                          self.generateRoute();
                      }
                  }
              });
      };
      self.resetSimpleSearch = function() {
          self.selectedCountryId(-1);
          self.selectedIndustryId(-1);
          self.selectedJobType(-1);
          self.profileAdvancedSearch(new ExpertProfileAdvancedSearch({ }));
          self.loadProfilesAdvancedSearchAll();
      };

      self.setDefaultSidebarIds = function() {
          self.selectedCountryId(-1);
          self.selectedIndustryId(-1);
      };

      //RESET SEARCH MODEL
      self.resetSearchModel = function() {
          self.workingProfileId(null);
          self.profileViewMode("list");
          self.profileAdvancedSearch().PageIndex(parent.pageIndexDefault);
          self.profileAdvancedSearch().PageSize(parent.pageSizeDefault);
          self.profileAdvancedSearch().CountryIds([]);
          self.profileAdvancedSearch().IndustryIds([]);
          self.profileAdvancedSearch().CategoryIds([]);
          self.profileAdvancedSearch().TechnologyIds([]);
      };

      self.generateRoute = function() {
          var id = self.workingProfileId();
          var mode = self.profileViewMode();
          var pageIndex = self.profileAdvancedSearch().PageIndex();
          var pageSize = self.profileAdvancedSearch().PageSize();
          var countryId = self.profileAdvancedSearch().CountryIds()[0];
          var industryId = self.profileAdvancedSearch().IndustryIds()[0];
          var catId = self.profileAdvancedSearch().CategoryIds()[0];
          var technologyId = self.profileAdvancedSearch().TechnologyIds()[0];
//        var xLoc = self.profileAdvancedSearch().XLocation();
//        var yLoc = self.profileAdvancedSearch().YLocation();
//        var radius = self.profileAdvancedSearch().Distance();
          var route = '#/Experts/?';
          var defaultRoute = route;
          if (id != null) {
              route = route + (defaultRoute != route ? '&' : '') + 'id=' + self.workingProfileId();
          }
          if (mode != null && mode != "" && mode != "advancedSearch") {
              route = route + (defaultRoute != route ? '&' : '') + 'mode=' + self.profileViewMode();
          }
          if (pageIndex != null && pageIndex != parent.pageIndexDefault && (mode == "list" || mode == "myList")) {
              route = route + (defaultRoute != route ? '&' : '') + 'pageIndex=' + pageIndex;
          }
          if (pageSize != null && pageSize != parent.pageSizeDefault && (mode == "list" || mode == "myList")) {
              route = route + (defaultRoute != route ? '&' : '') + 'pageSize=' + pageSize;
          }
          if (self.profileAdvancedSearch().CountryIds().length != 0 && self.profileAdvancedSearch().CountryIds()[0] != -1 && mode != "advancedSearch") {
              route = route + (defaultRoute != route ? '&' : '') + 'countryId=' + countryId;
          }
          if (self.profileAdvancedSearch().IndustryIds().length != 0 && self.profileAdvancedSearch().IndustryIds()[0] != -1 && mode != "advancedSearch") {
              route = route + (defaultRoute != route ? '&' : '') + 'industryId=' + industryId;
          }
          if (self.profileAdvancedSearch().CategoryIds().length != 0 && mode != "advancedSearch") {
              route = route + (defaultRoute != route ? '&' : '') + 'categoryId=' + catId;
          }
          if (self.profileAdvancedSearch().TechnologyIds().length != 0 && mode != "advancedSearch") {
              route = route + (defaultRoute != route ? '&' : '') + 'technologyId=' + technologyId;
          }
//        if (self.profileAdvancedSearch().XLocation() != 1000) {
//            route = route + (defaultRoute != route ? '&' : '') + 'xLoc=' + xLoc;
//        }
//        if (self.profileAdvancedSearch().YLocation() != 1000) {
//            route = route + (defaultRoute != route ? '&' : '') + 'yLoc=' + yLoc;
//        }
//        if (self.profileAdvancedSearch().Distance() != 0 && self.profileAdvancedSearch().Distance() != "") {
//            route = route + (defaultRoute != route ? '&' : '') + 'radius=' + radius;
//        }
          location.hash = route;
      };


      self.loadMyProfiles = function(pageIndex, pageSize, industryId, categoryId, technologyId) {
          $.getJSON("/ExpertProfile/MyList", { pageIndex: pageIndex, pageSize: pageSize, industryId: industryId, categoryId: categoryId, technologyId: technologyId }, function(allData) {
              self.pagesCountMyProfiles(allData.PagesCount);
              self.countMyProfiles(allData.Count);
              self.pagesCount(allData.PagesCount);
              self.count(allData.Count);
              var mappedProfiles = $.map(allData.Entities, function(item) { return new Profile(item); });
              self.myProfiles(mappedProfiles);
          });
      };


      //CREATEPROFILE BUTTON VISIBLE
      self.createProfileButton = ko.observable();
      self.cvShort = ko.observable("");
      self.cvShortWProfile = ko.observable("");
      self.description = ko.observable("");

      self.cvCheck = ko.computed(function() {
          if (self.workingProfile() != null) {
              if (self.workingProfile().Cv() != "Cv_default") {
                  self.cvShort(self.workingProfile().Cv().substring(self.workingProfile().Cv().lastIndexOf("/Cv/Cv_") + 7));
              } else {
                  self.cvShort("You haven't any file uploaded");
              }
          }
      });
      self.cvCheckWorkingProfile = ko.computed(function() {
          if (self.workingProfile() != null) {
              if (self.workingProfile().Cv() != "Cv_default") {
                  self.cvShortWProfile(self.workingProfile().Cv().substring(self.workingProfile().Cv().lastIndexOf("/Cv/Cv_") + 7));
              }
              self.cvShortWProfile("You haven't any file uploaded");
          }
      });
      self.descriptionCheck = ko.computed(function() {
          if (self.workingProfile() != null) {
              if (self.workingProfile().Description().length < 100) {
                  self.description(self.workingProfile().Description().substring(0, 100) + "...");
              }
          }
      });

      self.loadEducations = function() {
          $.getJSON("/ExpertProfile/GetJsonEducation", function(allData) {
              self.availableEducations(allData);
          });
      };
      self.loadCountries = function() {
          $.getJSON("/ExpertProfile/GetJsonCountry", function(allData) {
              self.availableCountries(allData);
          });
      };
      self.loadLanguageSkills = function() {
          $.getJSON("/ExpertProfile/GetJsonLanguageSkill", function(allData) {
              self.availableLanguageSkills(allData);
          });
      };
      self.availableLanguages = ko.observable();
      self.loadLanguages = function() {
          $.getJSON("/ExpertProfile/GetJsonLanguages", function(allData) {
              self.availableLanguages(allData);
          });
      };

      //UPLOAD PHOTO
      self.photo = ko.observable("");
      self.beforePhotoUpload = ko.observable(true);
      self.afterPhotoUpload = ko.observable(false);
      self.deletePhotoButton = ko.observable(false);
      self.uploadPhotoProgressBarVisible = ko.observable(false);
      self.resetPhotoUpload = function() {
          self.beforePhotoUpload(true);
          self.afterPhotoUpload(false);
          self.deletePhotoButton(false);
          self.photoAlertVisible(false);
          self.uploadPhotoProgressBarVisible(false);
          $('#dropZonePhoto').css('background', 'lightgray');
      };
      self.photoAlertVisible = ko.observable(false);
      self.dropPhoto = function() {
          $('#dropZonePhoto').filedrop({
                  url: 'Upload/UploadPhoto',
                  paramname: 'file',
                  maxFiles: 1,
                  maxfilesize: 5,
                  data: { profileId: self.workingProfile().Id() },
              //allowedfiletypes: ['image/jpg', 'image/png', 'image/gif'],
                  dragOver: function() {
                      $('#dropZonePhoto').css('background', 'white');
                  },
                  dragLeave: function() {
                      $('#dropZonePhoto').css('background', 'gray');
                  },
                  drop: function() {
                      $('#dropZonePhoto').css('background', 'gray');
                  },
                  progressUpdated: function(i, file, progress) {
                      // this function is used for large files and updates intermittently
                      // progress is the integer value of file being uploaded percentage to completion
                      self.uploadPhotoProgressBarVisible(true);
                      $("#uploadPhotoProfileProgressBar").width(progress + "%");
                      $("#uploadPhotoProfileProgressBar").width(100 + "%");
                  },
                  uploadFinished: function(i, file, response, time) {
                      self.workingProfileBuffer().Photo(response);
                      if (self.workingProfileBuffer().Photo.isValid()) {
                          $('#uploadPhotoResult').html('');
                          $('#uploadPhotoResult').html(file.name);
                          self.photo(response);
                          self.beforePhotoUpload(false);
                          self.afterPhotoUpload(true);
                      } else {
                          self.photoAlertVisible(true);
                      }
                  }
              });
      };
      //UPLOAD CV
      self.cv = ko.observable("");
      self.beforeCvUpload = ko.observable(true);
      self.afterCvUpload = ko.observable(false);
      self.cvAlertVisible = ko.observable(false);
      self.resetCvUpload = function() {
          self.beforeCvUpload(true);
          self.afterCvUpload(false);
          self.cvAlertVisible(false);
      };

      self.dropCv = function() {
          $('#dropZoneCv').filedrop({
                  url: 'Upload/UploadCv',
                  paramname: 'file',
                  maxFiles: 1,
                  maxfilesize: 5,
                  data: { profileId: self.workingProfile().Id() },
                  dragOver: function() {
                      $('#dropZoneCv').css('background', 'white');
                  },
                  dragLeave: function() {
                      $('#dropZonePhoto').css('background', 'gray');
                  },
                  drop: function() {
                      $('#dropZonePhoto').css('background', 'gray');
                  },
            //                afterAll: function() {
            //                    $('#dropZonePhoto').html('The file has been uploaded successfully!');
            //                },
                  uploadFinished: function(i, file, response, time) {
                      self.workingProfileBuffer().Cv(response);
                      if (self.workingProfile().Cv.isValid()) {
                          $('#uploadResultCv').html('');
                          $('#uploadResultCv').html(file.name);
                          self.cv(response);
                          self.beforeCvUpload(false);
                          self.afterCvUpload(true);
                      } else {
                          self.cvAlertVisible(true);
                      }
                  }
              });
      };

      self.gmapLocationAutocomplete = function() {
          $.when(loadGoogleMaps(3, null, null))
              .then(function() {
                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
                      $('#locationAutocompleteProfile').autocompleteG({
                              source: function() {
                                  $("#locationProfile").gmap3({
                                          action: 'getAddress',
                                          address: $(this).val() + ', ' + self.workingProfile().Country().Description,
                                          callback: function(results) {
                                              if (!results) return;
                                              $('#locationAutocompleteProfile').autocompleteG('display', results, false);
                                          }
                                      });
                                  $("#locationProfileViewMode").gmap3({
                                          action: 'getAddress',
                                          address: $(this).val() + ', ' + self.workingProfile().Country().Description,
                                          callback: function(results) {
                                              if (!results) return;
                                              $('#locationAutocompleteProfile').autocompleteG('display', results, false);
                                          }
                                      });
                                  $("#locationProfileEditMode").gmap3({
                                          action: 'getAddress',
                                          address: $(this).val() + ', ' + self.workingProfile().Country().Description,
                                          callback: function(results) {
                                              if (!results) return;
                                              $('#locationAutocompleteProfile').autocompleteG('display', results, false);
                                          }
                                      });
                              },
                              cb: {
                                  cast: function(item) {
                                      return item.formatted_address;
                                  },
                                  select: function(item) {
                                      $("#locationProfile").gmap3(
                                          { action: 'clear', name: 'marker' },
                                          { action: 'addMarker', latLng: item.geometry.location },
                                          { action: 'setCenter', args: [item.geometry.location] },
                                          { action: 'clear', name: 'InfoWindow' },
                                          {
                                              action: 'addInfoWindow',
                                              address: $(this).val(),
                                              map: {
                                                  center: true,
                                                  zoom: 10
                                              },
                                              infowindow: {
                                                  options: { content: $(this).val() }
                                              }
                                          });
                                      $("#locationProfileViewMode").gmap3(
                                          { action: 'clear', name: 'marker' },
                                          { action: 'addMarker', latLng: item.geometry.location },
                                          { action: 'setCenter', args: [item.geometry.location] });
                                      $("#locationProfileEditMode").gmap3(
                                          { action: 'clear', name: 'marker' },
                                          { action: 'addMarker', latLng: item.geometry.location },
                                          { action: 'setCenter', args: [item.geometry.location] });
                                  }
                              }
                          });
                  });
              });
      };

//      //SELECT LOCATION
//      self.selectSelectLocation = function() {
//          $.when(loadGoogleMaps(3, null, null))
//              .then(function() {
//                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
//                      var loc = "";
//                      $("#selectLocationProfile").gmap3();
//                  });
//              });
//          self.gmapSelectLocationAutocomplete();
//      };
//      self.okSelectLocation = function() {
//          self.profileAdvancedSearch().Location($('#selectLocationAutocompleteProfile').val());
//          $('#selectLocationAutocompleteProfile').val("");
//          $("#SelectLocationDialog").modal("hide");
//      };
//      self.cancelSelectLocation = function() {
//          $("#SelectLocationDialog").modal("hide");
//      };

//      self.gmapSelectLocationAutocomplete = function() {
//          $.when(loadGoogleMaps(3, null, "hr"))
//              .then(function() {
//                  $.cachedScript("../../Scripts/gmap3/gmap3.min.js").done(function() {
//                      $('#selectLocationAutocompleteProfile').autocompleteG({
//                              source: function() {
//                                  $("#selectLocationProfile").gmap3({
//                                          action: 'getAddress',
//                                          address: $(this).val(),
//                                          callback: function(results) {
//                                              if (!results) return;
//                                              $('#selectLocationAutocompleteProfile').autocompleteG('display', results, false);
//                                          }
//                                      });
//                              },
//                              cb: {
//                                  cast: function(item) {
//                                      return item.formatted_address;
//                                  },
//                                  select: function(item) {
//                                      $("#selectLocationProfile").gmap3(
//                                          { action: 'clear', name: 'marker' },
//                                          { action: 'addMarker', latLng: item.geometry.location },
//                                          { action: 'setCenter', args: [item.geometry.location] },
//                                          {infowindow:
//                                              { options: { content: '<div id="content" style="width:300px;height:250px;"></div>' } }
//                                          });

//                                      self.profileAdvancedSearch().XLocation(item.geometry.location.Xa);
//                                      self.profileAdvancedSearch().YLocation(item.geometry.location.Ya);
//                                   }
//                              }});
//                  });
//              });
//      };

      //AUTOCOMPLETE
      self.autocompleteIndustries = function() {
          $("#industriesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Industry/GetIndustriesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.industryTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.industryTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().IndustryIds.push(id);
                      }

                      $("#industriesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllIndustries = function() {
          $("#industriesExpertsAutocomplete").autocomplete("search", "");
          $("#industriesExpertsAutocomplete").focus();
      };
      self.removeIndustryTag = function(tag) {
          self.industryTags.remove(tag);
          self.profileAdvancedSearch().IndustryIds.remove(function(item) { return item == tag.Id; });
      };

      self.autocompleteCategories = function() {
          $("#categoriesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Category/GetCategoriesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.categoryTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.categoryTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().CategoryIds.push(id);
                      }

                      $("#categoriesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllCategories = function() {
          $("#categoriesExpertsAutocomplete").autocomplete("search", "");
          $("#categoriesExpertsAutocomplete").focus();
      };
      self.removeCategoryTag = function(tag) {
          self.categoryTags.remove(tag);
          self.profileAdvancedSearch().CategoryIds.remove(function(item) { return item == tag.Id; });
      };

      self.autocompleteTechnologies = function() {
          $("#technologiesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Technology/GetTechnologiesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Name,
                                          value: item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.technologyTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.technologyTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().TechnologyIds.push(id);
                      }

                      $("#technologiesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllTechnologies = function() {
          $("#technologiesExpertsAutocomplete").autocomplete("search", "");
          $("#technologiesExpertsAutocomplete").focus();
      };
      self.removeTechnologyTag = function(tag) {
          self.technologyTags.remove(tag);
          self.profileAdvancedSearch().TechnologyIds.remove(function(item) { return item == tag.Id; });
      };


      self.autocompleteCountries = function() {
          $("#countriesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Country/GetCountriesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.TitleTranslation,
                                          value: item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.countryTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.countryTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().CountryIds.push(id);
                      }

                      $("#countriesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllCountries = function() {
          if (self.countryTags().length == 0) {
              $("#countriesExpertsAutocomplete").autocomplete("search", "");
              $("#countriesExpertsAutocomplete").focus();
          } else {
              $("#countriesExpertsAutocomplete1").autocomplete("search", "");
              $("#countriesExpertsAutocomplete1").focus();
          }
      };
      self.removeCountryTag = function(tag) {
          self.countryTags.remove(tag);
          self.profileAdvancedSearch().CountryIds.remove(function(item) { return item == tag.Id; });
      };

      self.autocompleteEducations = function() {
          $("#educationsExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Education/GetEducationsAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.educationTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.educationTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().EducationIds.push(id);
                      }

                      $("#educationsExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllEducations = function() {
          $("#educationsExpertsAutocomplete").autocomplete("search", "");
          $("#educationsExpertsAutocomplete").focus();
      };

      self.removeEducationTag = function(tag) {
          self.educationTags.remove(tag);
          self.profileAdvancedSearch().EducationIds.remove(function(item) { return item == tag.Id; });
      };

      self.autocompleteLanguages = function() {
          $("#languagesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "Language/GetLanguagesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var id = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.languageTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.languageTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().LanguageIds.push(id);
                      }

                      $("#languagesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllLanguages = function() {
          $("#languagesExpertsAutocomplete").autocomplete("search", "");
          $("#languagesExpertsAutocomplete").focus();
      };
      self.removeLanguageTag = function(tag) {
          self.languageTags.remove(tag);
          self.profileAdvancedSearch().LanguageIds.remove(function(item) { return item == tag.Id; });
      };

      self.autocompleteEmploymentTypes = function() {
          $("#employmentTypesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "ExpertProfile/GetJobTypesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Value
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var value = ui.item.value;
                      var description = ui.item.label;

                      var found = ko.utils.arrayFirst(self.employmentTypeTags(), function(item) {
                          return item.Description == description;
                      });
                      if (!found) {
                          self.employmentTypeTags.push({ Value: value, Description: description });
                          self.profileAdvancedSearch().JobTypes.push(value);
                      }
                      var jobType;
                      if (self.profileAdvancedSearch().JobTypes().length == 0) {
                          jobType = 0;
                      } else {
                          jobType = self.profileAdvancedSearch().JobTypes()[0].Value;
                          for (var i = 1; i < self.profileAdvancedSearch().JobTypes().length; i++) {
                              jobType = jobType | self.profileAdvancedSearch().JobTypes()[i].Value;
                          }
                      }
                      self.profileAdvancedSearch().JobType(jobType);
                      $("#employmentTypesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllEmploymentTypes = function() {
          $("#employmentTypesExpertsAutocomplete").autocomplete("search", "");
          $("#employmentTypesExpertsAutocomplete").focus();
      };
      self.removeEmploymentTypeTag = function(tag) {
          self.employmentTypeTags.remove(tag);
          self.profileAdvancedSearch().EmploymentTypes.remove(function(item) { return item == tag.Value; });
      };

      self.autocompleteAvailabilityStatuses = function() {
          $("#availabilityStatusesExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "ExpertProfile/GetAvailabilityStatusesAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Value
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var value = ui.item.value;
                      var description = ui.item.label;

                      self.availabilityStatusTag({ Value: value, Description: description });
                      self.profileAdvancedSearch().AvailabilityStatus(value);
                      $("#availabilityStatusesExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.showAllAvailabilityStatuses = function() {
          $("#availabilityStatusesExpertsAutocomplete").autocomplete("search", "");
          $("#availabilityStatusesExpertsAutocomplete").focus();
      };
      self.removeAvailabilityStatusTag = function(tag) {
          self.availabilityStatusTag(null);
          self.profileAdvancedSearch().AvailabilityStatus(tag.Value);
      };

      self.autocompleteKeywords = function() {
          $("#keywordsExpertsAutocomplete").autocomplete({
                  source: function(request, response) {
                      $.ajax({
                              url: "ExpertProfile/GetKeywordsAutocomplete",
                              dataType: "json",
                              data: {
                                  searchTerm: request.term,
                                  maxRows: 8
                              },
                              success: function(data) {
                                  response($.map(data, function(item) {
                                      return {
                                          label: item.Description,
                                          value: item.Type + item.Id
                                      };
                                  }));
                              }
                          });
                  },
                  minLength: 0,
                  select: function(event, ui) {
                      var description = ui.item.label;
                      var type = ui.item.value.substring(0, 2);
                      var id = ui.item.value.substring(2);
                      if (type == "co") {
                          self.countryTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().CountryIds.push(id);
                      } else if (type == "in") {
                          self.industryTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().IndustryIds.push(id);
                      } else if (type == "ca") {
                          self.categoryTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().CategoryIds.push(id);
                      } else if (type == "te") {
                          self.technologyTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().TechnologyIds.push(id);
                      } else if (type == "ed") {
                          self.educationTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().EducationIds.push(id);
                      } else if (type == "la") {
                          self.languageTags.push({ Id: id, Description: description });
                          self.profileAdvancedSearch().LanguageIds.push(id);
                      }
                      if (event.keyCode == 13) {
                          self.enterKeyPressed = true;
                      }
                      $("#keywordsExpertsAutocomplete").val("");
                      return false;
                  },
                  focus: function(event, ui) {
                      this.value = ui.item.label;
                      event.preventDefault(); // Prevent the default focus behavior.
                  }
              });
      };
      self.addKeywordTag = function() {
          self.keywordTags.push({ Description: self.keyword() });
          self.profileAdvancedSearch().Keywords.push(self.keyword());
          var tag = $.Enumerable.From(self.keywordTags()).SingleOrDefault(null, function(x) {
              return self.keyword() === x.Description;
          });
          //if enter key is not pressed while selection => remove tag from keywordTags
          if (self.enterKeyPressed) {
              self.keywordTags.remove(tag);
              self.profileAdvancedSearch().Keywords.remove(function(item) { return item == self.keyword(); });
          }
          self.enterKeyPressed = false;
          $("#keywordsExpertsAutocomplete").val("");
          return false;
      };
      self.removeKeywordTag = function(tag) {
          self.keywordTags.remove(tag);
          self.profileAdvancedSearch().Keywords.remove(function(item) { return item == tag.Description; });
      };


  }